import { createApp, ref, TeleportProps } from "vue";
import type { Ref, App } from "vue";
import MyLoading from "./Loading.vue";
// 定义一个Loading类，用于管理Loading状态
export default class Loading {
  loading: Ref<boolean>;
  container: Element;
  teleport: TeleportProps["to"];
  loadingComponent: App<Element> | null;
  basicProps: Record<string, any> = {};
  /**
   * @description: 初始化容器，挂载到body上
   */
  constructor(teleport?: TeleportProps["to"]) {
    const container = document.createElement("div");
    this.teleport = teleport || "body";
    this.container = container;
    this.loadingComponent = null;
    this.loading = ref(false);
  }
  setLoadingProps(props: Record<string, any>) {
    this.basicProps = props;
  }
  /**
   * @description: 开启Loading状态
   * @param {Record<string, unknown>} rootProps 可传入根结点的属性，比如class，text，horizontal等
   */
  start(rootProps?: Record<string, unknown>) {
    this.stop();
    this.loading.value = true;
    this.teleport = rootProps?.teleport || "body";
    if (this.teleport) {
      let node = this.teleport;
      if (typeof node === "string") {
        node = document.querySelector(node) || document.body;
      }
      if (typeof node !== "string") node.style.overflow = "hidden";
    }
    this.loadingComponent = createApp(
      MyLoading,
      Object.assign({}, this.basicProps, rootProps, { teleport: this.teleport })
    );
    if (this.container && this.loadingComponent) {
      this.loadingComponent.mount(this.container);
    }
  }
  /**
   * @description: 关闭Loading状态
   */
  stop() {
    if (this.loading.value) {
      this.loading.value = false;
      if (this.teleport) {
        let node = this.teleport;
        if (typeof node === "string") {
          node = document.querySelector(node) || document.body;
        }
        if (typeof node !== "string") node.style.overflow = "auto";
      }
    }
    if (this.loadingComponent) {
      this.loadingComponent.unmount();
    }
  }
}
